package com.ihk.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;

import android.util.Log;

public class SearchGeoCoder {
	
	private final static String ENCODING = "UTF-8";
	private final static String KEY = "05IwLSbJmbfNskuHOLbJeRVmV4VcrABY9C1fCuw";
		
	public static UserLocation getLocation (String address) throws IOException {
		BufferedReader in = new BufferedReader (new InputStreamReader (new URL ("http://maps.google.com/maps/geo?q="+URLEncoder.encode (address, ENCODING)+"&output=csv&key="+KEY).openStream ()));
		String line;
		UserLocation location = UserLocation.getInstance();
		int statusCode = -1;
		
		while ((line = in.readLine ()) != null) 
		{
			
			// Format: 200,6,42.730070,-73.690570
			
		    String[] cols = line.split(",");
		    
			statusCode = Integer.parseInt (cols[0]);
			if (statusCode == 200)
			
			location.setLatitude(Double.parseDouble(cols[2]));
			Log.d("ToiletFinder", "Double longitude : result = " + Double.valueOf(cols[2]));
			
			location.setLongitude(Double.parseDouble(cols[3]));
			Log.d("ToiletFinder", "Double latitude : result = " + Double.valueOf(cols[3]));
			
		}
		
		if (location == null) {
			switch (statusCode) {
				case 400: throw new IOException ("Bad Request");
				case 500: throw new IOException ("Unknown error from Google Encoder");
				case 601: throw new IOException ("Missing query");
				case 602: return null;
				case 603: throw new IOException ("Legal problem");
				case 604: throw new IOException ("No route");
				case 610: throw new IOException ("Bad key");
				case 620: throw new IOException ("Too many queries");
			}
		}
		return location;
	}
}